/**
 * Course page javascript methods 
 */

$(document).ready(function() { 
	/**
	 * Bind triggers to editor DOM elements
	 */
    /**
     * Edit object methods
     */
    $(".note-edit").live('click', function() {
        var $id = getObjectID($(this).attr("id"));
        editCourseObject($("#note-" + $id), "tasks/note/editor", "id=" + $id + "&ajax=1");
        return false;
    }); // Edit note
    
    $(".assignment-edit").live('click', function() {
        var $id = getObjectID($(this).attr("id"));
        editCourseObject($("#assignment-" + $id), "tasks/item/editor", "id=" + $id + "&ajax=1");
        return false;
    }); // Edit note

    /**
     * Remove object methods
     */
    $(".assignment-remove").live('click', function() {
        var $id = getObjectID($(this).attr("id"));
        removeObject($("#assignment-" + $id), $(this).attr("href") + "/ajax", "", Lang.assignments_remove_prompt, true)
        return false;
    }); // Remove assignment
    
    $(".remove-file-course").live('click', function() {
        var $id = getObjectID($(this).attr("id"));
        removeObject($("#file-" + $id), $(this).attr("href") + "/ajax", "", Lang.files_remove_prompt, true)
        return false;
    }); // Remove file
    
    $(".link-remove").live('click', function() {
        var $id = getObjectID($(this).attr("id"));
        removeObject($("#link-" + $id), $(this).attr("href") + "/ajax", "", Lang.links_remove_prompt, true)
        return false;
    }); // Remove link
    
    $(".note-remove").live('click', function() {
        var $id = getObjectID($(this).attr("id"));
        removeObject($("#note-" + $id), $(this).attr("href") + "/ajax", "", Lang.notes_remove_prompt, true)
        return false;
    }); // Remove note
    
    $(".sharing-remove img").live('click', function() {
        var loc = $(this).parent().attr('href');
        modalConfirm(Lang.sharing_remove_prompt, function() { window.location = loc; });
        return false;
    }); // Remove shared user
    
    /**
     * Assignment methods
     */
    $(".assignment-check").live("click", function() {
        var $id = getObjectID($(this).attr("id"));
        var $td = $(this).parent();
        $.post($(this).attr('href') + '/ajax', '', function(data) {
            if (!errorHandle(data)) {
                $td.html(data.html);
                $td.next().next().find("span").toggleClass('strike'); 
            }
        }, "json");
        return false;
    }); // Complete/Restore assignment
	
	/**
	 * Element specific events
	 */
	$("#new-item-note-title").focus( function() {
		$("#new-item-note-form-extras").show();
	});
	
	$('.assignment-add-note').click( function(e) {
		$('#new-assignment-note').toggle();
		location.hash = 'notes';
	});
	
	$('#new-item-note-form-extras .action-cancel').click( function() {
		$('#new-assignment-note').hide();
	});
	
	$(".sharing-check").click( function() { 
		$(this).parent().parent().toggleClass("selected"); 
		$(this).parent().parent().find(".share-select").toggleClass("hide-share-select");
	});
	
	if ($("#sharing-browse-form").length) {
		$("#sharing-browse-form .sharing-check").clearFields();
	}
	
	$(".color-dropdown-course").live('click', function (e) {
		var position = $(this).position();
		$("#color_picker").css({ 'top': position.top + 15, 'left': position.left + 3 });
		$("#tid").val(getObjectID($(this).attr("id")));
		$("#color_picker").toggle();
	});
	
    if ($("#assignments-list-table").length) {
    	$("#assignments-list-table").tablesorter({ 
    		headers: { 
    			0: { sorter: false}, 
    			4: { sorter: false} 
    		}
    	});
    }
    
	/* Feed effects */
    $('.reminder').live('click', function() {
    	var assn_id = $(this).attr('id').replace('assignment-reminder-', '');
		var course_id = $(this).parent().parent().attr('course');
    	var itemName = $("#assignment-name-" + assn_id).val();
		var dueDate = $("#assignment-date-" + assn_id).attr('title');
		var timeHour = '';
		var timeMinute = '';
		var timeAMPM = '';				
		// Change loader icon
		$('#assignment-'+assn_id+' .feed-type a').hide();
		$('#assignment-'+assn_id+' .feed-type .loader').show();
		// Show the modal
		addReminder(itemName, dueDate, timeHour, timeMinute, timeAMPM, 'assignment', assn_id, course_id);
    });
	
	$('.editnote').live('click', function() {
		var i = $(this).parent().parent().attr('id').replace('note-','');
		var c = $(this).parent().parent().attr('course');
		// Change loader icon
		$('#note-'+i+' .feed-type .noteicon').hide();
		$('#note-'+i+' .feed-type .loader').show();
		// Show the modal
		$.post("tasks/note/editor", "id="+i+"&ajax=1",
			function(data) {
				if (errorHandle(data)) return false;
				$("#modal-window .title-header").html("Edit Note");
				$("#modal-window .message").html(data.html);
				$("#course-id-holder").attr("value",c);
				$("#modal-window #modal-window-action-button span").html('Edit note');
				$("#modal-window #modal-window-action-button").click(function() { $(".modal-form").submit(); });
				$("#modal-window .simplemodal-close").attr('value','Close');
				$("#modal-window .buttons").show();
				$("#modal-window").modal({overlayClose:true});
				// Hide the loader
				$('#note-'+i+' .feed-type .loader').hide();
				$('#note-'+i+' .feed-type .noteicon').show();
				// Bind the editor
				courseEditObjectsBind();
				return true;
			}, "json");
		return false;
	});
	
	$('.editassignment').live('click', function() {
		var i = $(this).attr('id').replace('assignment-edit-','');
		var c = $(this).parent().parent().attr('course');
		var r = $(this).attr('ref');
		// Change loader icon
		if (r == 'feed') {
			$('#assignment-'+i+' .feed-type a').hide();
			$('#assignment-'+i+' .feed-type .loader').show();
		}
		// Show the modal
		$.post("tasks/item/editor", "id="+i+"&ref="+r+"&ajax=1",
			function(data) {			
				if (errorHandle(data)) return false;
				$("#modal-window .title-header").html("Edit Assignment");
				$("#modal-window .message").html(data.html);
				$("#course-id-holder").attr("value",c);
				$("#modal-window #modal-window-action-button span").html('Save Assignment');
				$("#modal-window #modal-window-action-button").click(function() { $(".modal-form").submit(); });
				$("#modal-window .simplemodal-close").attr('value','Close');
				$("#modal-window .buttons").show();
				$(".edit-item-date").datepicker({ duration: '' });
				$("#modal-window").modal({overlayClose:true});
				// Hide the loader
				$('#assignment-'+i+' .feed-type .loader').hide();
				$('#assignment-'+i+' .feed-type a').show();
				// Bind the editor
				courseEditObjectsBind();
				return true;
			}, "json");
		return false;
	});
	
	/* Item search */
	$('#search-items-box').keyup(function () {
		var keyword = $(this).val().toLowerCase();
		if (keyword.length > 3 || keyword.length == 0) {
			filterCourseItems(keyword);
		}		
	});
	
	$('.clear-search').click(function () {
		$('.feed-search input').val('');
		filterCourseItems('');
	});
	
	/* Filter options */
	$('#feed-check-desc').click(function() {
		toggleDesc();
	});
	$('#feed-check-user').click(function() {
		if ($(this).is(':checked')) {
			$('.feed-links').removeClass('hide');
		} else {
			$('.feed-links').addClass('hide');
		}
	});
	$('#feed-check-comp').click(function() {
		toggleComp();
	});
	$('#course-filter-all').click(function() {
		$('input.feed-filter').attr('checked','checked')
	})
	
	/* Checkbox filter */
	$('.feed-filter').click(function() {
		refreshStream();	
	});
	
	/* Link filter - only show that type */
	$('.filter-only').click(function() {
		var params = $(this).attr('rel');
		var sort = $('#sort-dd').val();
		var course = $('#course-id').val();
		var keyword = $('#search-items-box').val();
		$('.feed-filter[alt!='+params+']').attr('checked',false);
		$('.feed-filter[alt='+params+']').attr('checked','checked');
		$('#course-feed-loader').show();
		loadActivities(course, params, keyword, sort, true);
	});
	
	/* Sort feed items */
	$('#sort-dd').change(function() {
		refreshStream();
	})
	
	/* Actions mouseover */
	$('.feed-item').live('mouseover', function() {
		$(this).children('.feed-actions').show();
	});
	$('.feed-item').live('mouseout', function() {
		$(this).children('.feed-actions').hide();
	});
	
	/* Initial page load, populate the feed based on checks. Disable for pages with
	 * flag set */
	if ((! $('#disable-stream').length || ! $('#disable-stream').val()) && $('#class-feed').length) {
		refreshStream();
	}
});

/**
 * Feed functions
 */
function toggleDesc() {
	if ($("#feed-check-desc").is(':checked')) {
		$('.feed-desc').show();
	} else {
		$('.feed-desc').hide();
	}
}

function toggleComp() {
	if ($("#feed-check-comp").is(':checked')) {
		$('.feed-item.assignment[status="1"]').show();
	} else {
		$('.feed-item.assignment[status="1"]').hide();
	}
}

function refreshStream() {
	var params = '';
	var sort = $('#sort-dd').val();
	var course = $('#course-id').val();
	var keyword = $('#search-items-box').val();
	$('input.feed-filter').each(function() {
		if ($(this).is(':checked')) {
			params = params + $(this).val() + ','
		}
	});
	params = params.substring(0, params.length - 1);
	$('#course-feed-loader').show();
	loadActivities(course, params, keyword, sort, true);
}

function loadActivities(course, params, keyword, sort, clear) {
	$.ajax({
		url: gm_baseurl + "tasks/course/feed/0/30",
		type: "POST",
		data: ({ course_id: course, filters: params, keyword: keyword, sort: sort }),
		dataType: "html",
		async: true,
		success: function(data){
			$('#course-feed-loader').hide();
			if (errorHandle(data)) 
				return false;
			if (clear)
				$('#class-feed').html('');
			$('#class-feed').append(data);
			toggleDesc();
			toggleComp();
			return true;
		},
		error: function(xhr, status, error){
		    if (error && error.length) {
		        $('#ajax-error').html('<span>Sorry, there was a problem.</span>').fadeIn();
		    }
			$('#course-feed-loader').hide();
		}
	});

}
function filterCourseItems(keyword) {
	$('.feed-item .feed-info').each(function () {
		if ($(this).text().toLowerCase().indexOf(keyword) > -1) {
			$(this).parent().show();
		} else {
			$(this).parent().hide();
		}
	});
}

function dateAddedSort(a, b) {
	if ($(a).attr('added') > $(b).attr('added'))
		return -1;
	else
		return 1;
}
function dateDueSort(a, b) {
	if ($(a).attr('due') > $(b).attr('due'))
		return -1;
	else
		return 1;
}
function dateModifiedSort(a, b) {
	if ($(a).attr('modified') > $(b).attr('modified'))
		return -1;
	else
		return 1;
}

function editCourseObject(elt, url, par, msg) {
	elt.find(".icon").hide();
	elt.find(".loader").show();
	$.post(url, par,
  		function(data) {			
			elt.find(".loader").hide();
			elt.find(".icon").show();
			if (errorHandle(data)) return false;
			elt.hide();
			if (! $("#" + data.elt_id).length) elt.after(data.html);
			courseEditObjectsBind();
  		}, "json");
}

/**
 * Add object methods / AJAX forms
 */
function toggleActive(i) {
	$('.unified-more-'+i+' .indicator').show();
	$('#add-'+i+'-submit').addClass("gb db disabled").attr("disabled","disabled");
}

function toggleInactive(i) {
	$('.unified-more-'+i+' .indicator').hide();
	$('#add-'+i+'-submit').removeClass("gb db disabled").removeAttr("disabled");
	if (i != 'file') $('.unified-more-'+i+'').hide();
	$('.form-more').hide();
	$('.unified-show-more-a').show();
}

// Assignment
$("#add-assignment").ajaxForm({
	url: 'tasks/item/add/ajax',
	dataType: 'json',
	beforeSubmit: function() {
		toggleActive('assignment');
	},
	success: function(data) {
		// Show/hide some elements
		toggleInactive('assignment');
		
		// Error handling
		if (errorHandle(data)) return false;
		
		// Post a reminder form if it was checked
		if ($("#add-assignment-reminder").is(':checked')) {
			t = $("#add-assignment-title").val();
			d = $("#add-assignment-date").val();
			h = $("#add-assignment-hour").val();
			m = $("#add-assignment-minute").val();
			a = $("#add-assignment-ampm").val();				
			addReminder(t, d, h, m, a, 'assignment', data.id, '');
		}
		
		// Show the new data
		$("#class-feed .feed-item:first").before($(data.html).hide().fadeIn(500));
		if ($(".no-items").length) $(".no-items").remove();
		$("#add-assignment-title").val("");
		$("#add-assignment-description-text").val("");
		courseObjectsBind();
		return true;
	}
});

// Note
$("#new-note").ajaxForm({
	url: 'tasks/note/add/ajax',
	dataType: 'json',
	beforeSubmit: function() {
		toggleActive('note');
	},
	success: function(data) {
		// Show/hide some elements
		toggleInactive('note');
		
		// Error handling
		if (errorHandle(data)) return false;
		
		// Show the new data
		$("#class-feed .feed-item:first").before($(data.html).hide().fadeIn(500));
		if ($(".no-items").length) $(".no-items").remove();
		$("#new-note-title").val("");
		$("#new-note-body").val("");
		courseObjectsBind();
		return true;
	}
});

$("#new-item-note-form").ajaxForm({
	url: 'tasks/note/add/ajax/assignment',
	dataType: 'json',
	beforeSubmit: function() {
		$('#new-item-note-loader').show();
	},
	success: function(data) {
		$('#new-item-note-loader').hide();
		if (errorHandle(data)) return false;
		$('#new-assignment-note').hide();
		
		// Show the new data
		if ($("#no-notes").length) $("#no-notes").remove();
		$("#notes-list-table").prepend(data.html);
		$("#new-item-note-title").val("");
		$("#new-item-note-body").val("");
		courseObjectsBind();
		return true;
	}
});

// File
$("#new-file").ajaxForm({
    url: 'tasks/file/upload/ajax',
	dataType: 'json',
	iframe: true,
	beforeSubmit: function(a, f, o) {
		toggleActive('file');
	},
	success: function(data) {
		// Cleanse
		var html = URLDecode(data.html);

		// Show/hide some elements
		toggleInactive('file');

		// Error handling
		if (errorHandle(data)) return false;
		
		// Show the new data
		$("#class-feed .feed-item:first").before(html);
		if ($(".no-items").length) $(".no-items").remove();
		$("#new-file-path").val("");
		courseObjectsBind();
		return true;
	}
});

// Bookmark
$("#new-bookmark").ajaxForm({
	url: 'tasks/link/add/ajax',
	dataType: 'json',
	beforeSubmit: function() {
		toggleActive('bookmark');
	},
	success: function(data) {
		// Show/hide some elements
		toggleInactive('bookmark');
		
		// Error handling
		if (errorHandle(data)) return false;
		
		// Show the new data
		$("#class-feed .feed-item:first").before($(data.html).hide().fadeIn(500));
		if ($(".no-items").length) $(".no-items").remove();
		$("#new-link-title").val("");
		$("#new-link-url").val("");
		courseObjectsBind();
		return true;
	}
});

function courseObjectsBind() {
}

function courseEditObjectsBind() {
	$(".edit-note").each( function () {
		var elt = $(this);
		var id = getObjectID($(this).attr("id"));
		var feed_elt = $('#note-' + id);

		$(this).ajaxForm({
			url: 'tasks/note/edit/ajax',
			dataType: 'json', 
			beforeSubmit: function() {
				$('#modal-window-loader').show();
			},
			success: function(data) {
				$('#modal-window-loader').hide();
				if (!errorHandle(data)) {
					feed_elt.attr('id', '#note-' + id + '-temp');
					feed_elt.hide();
					feed_elt.after(data.html);
					feed_elt.remove();
					$.modal.close();
				}
				courseObjectsBind();
			}
		});

		$(this).find(".action-cancel").click( function() {
			elt.hide();
			elt.prev().show();
			elt.remove();
		});
	}); // Edit note
	
	$(".edit-assignment").each( function() {
		// Set some variables
		var elt = $(this);
		var id = getObjectID($(this).attr("id"));
		var item = $('#assignment-' + id);
		var ref = (elt.attr("ref") == 'item') ? "item" : "feed";
		
		// Post the form
		$(this).ajaxForm({
			url: 'tasks/item/edit/ajax',
			dataType: 'json', 
			beforeSubmit: function() {
				$('#modal-window-loader').show();
			},
			success: function(data) {
				$('#modal-window-loader').hide();
				if (!errorHandle(data)) {
					item.attr('id', '#assignment-' + id + '-temp');
					item.hide();
					item.after(data.html);
					item.remove();
					$.modal.close();
				}
				courseObjectsBind();
			}
		});
		
		$(this).find(".action-cancel").click( function() {
			elt.hide();
			elt.prev().show();
			elt.remove();
		});
	}); // Edit assignment
	
	$(".add-reminder").each( function() {
		$(this).ajaxForm({
			url: 'tasks/reminder/add/ajax',
			dataType: 'json',
			beforeSubmit: function() {
				$('#modal-window-loader').show();
			},
			success: function(data) {
				$('#modal-window-loader').hide();
				if (!errorHandle(data)) {
					$.modal.close();
				}
			}
		});
		return false;
	});
		
	$(".edit-item-date").each( function() {
		$(this).datepicker({ duration: '' });
	});
}

function addReminder(title, dueDate, timeHour, timeMinute, timeAMPM, objectType, objectId, courseId) {
	$.ajax({
		url: gm_baseurl + "tasks/course/addreminder",
		type: "POST",
		data: ({itemTitle: title, dueDate: dueDate, timeHour: timeHour, timeMinute: timeMinute, ampm: timeAMPM, 
				objectType: objectType, objectId: objectId, ajax: 1, modal: 'modal'}),
		dataType: "html",
		async: true,
		success: function(data){
			$("#modal-window .title-header").html(Lang.assignments_add_reminder);
			$("#modal-window .message").html(data);
			$("#course-id-holder").attr("value",courseId);
			$("#modal-window #modal-window-action-button span").html('Create this reminder');
			$("#modal-window #modal-window-action-button").click(function() { $(".reminder-form").submit(); });
			$("#modal-window .simplemodal-close").attr('value','Close');
			$("#modal-window .buttons").show();
			$(".edit-item-date").datepicker({ duration: '' });
			if (objectType == 'assignment') {
				$('#assignment-'+objectId+' .feed-type .loader').hide();
				$('#assignment-'+objectId+' .feed-type a').show();	
			}
			$("#modal-window").modal({overlayClose:true});
			courseEditObjectsBind();
		},
		error: function(xhr, status, error){
			$('#ajax-error').html('<span>'+Lang.rubric_baddetails+'</span>').fadeIn();
			//loader.hide();
		}
	});
}

$(".add-assignment-title").focus( function() { 
	$("#new-item-description").show();
});

function saveAssignmentTypeColor(color_id, fg_color, bg_color) {
	var type_id = $("#tid").val();
	var input = "#type-color-" + type_id;
	var elt = "#color-chosen-" + type_id
	$(input).val(color_id);
	$(elt).css("background-color", bg_color);
	$(elt).css("color", fg_color);
	$(elt).css("border-color", fg_color);
	$("#color_picker").toggle();
}

/**
 * Course edit page
 */
$('#course-add-type').live('click',  function(e) {
	var html = $('#blank-assignment-type').html();
	$('#blank-assignment-type').html('');
	$("#modal-window .message").html(html);
	$("#modal-window .title-header").html(Lang.courses_new_type_header);
	$('#modal-window-action-button').val(Lang.courses_add_type);
	$('#modal-window-action-button').addClass('add-type-confirm');
	
	$('#modal-window .buttons').show();
	$('#modal-window').addClass('prompt');
	$("#modal-window").modal({
		overlayClose:true,
		onClose: function (dialog) {
			closeAssignmentTypesModal();
			$.modal.close(); // must call this!
		}
	});
	e.preventDefault();
});

$('.add-type-confirm').live('click', function(e) {
	$('#modal-window-loader').show();
	$('#new-type-error').hide();
	$.post('tasks/type/add/' + $('#new-type-course-id').val(), "name=" + $('#new-type-name').val() + "&ajax=1", function(data) {
		$('#modal-window-loader').hide();
		if (data.status == "error") {
			$('#new-type-error').html(URLDecode(data.message));
			$('#new-type-error').show();
		} else {
			$('#types-list tr:last').before(data.html);
			$.modal.close();
		}
	}, "json");
});

function closeAssignmentTypesModal() {
	var html = $('#modal-window .message').html();
	$('#modal-window').removeClass('prompt');
	$('#modal-window-action-button').removeClass('add-type-confirm');
	$('#modal-window .message').html('')
	$("#modal-window .title-header").html(Lang.error_problem);
	$("#blank-assignment-type").html(html);
	$('#modal-window-loader').hide();
	$('#new-type-error').hide();
}

$('#course-edit-show-a').click( function(e) {
	$('#course-edit-show').hide();
	$('#course-edit-hide').fadeIn();
	e.preventDefault();
	return false;
});

/**
 * Attendance
 */
$('.attendance-change').live('click', function(e) {
	var type = $(this).find('.attendance-type').val();
	var date = $(this).find('.attendance-date').val();
	var student_id = $(this).find('.attendance-student-id').val();
	var lang_line = $(this).find('span').html();
	var new_type = 'present';
	var new_lang_line = Lang.attendance_present;
	
	if (type == 'present') {
		new_type = 'late';
		new_lang_line = Lang.attendance_late;
	}
	else if (type == 'late') {
		new_type = 'absent';
		new_lang_line = Lang.attendance_absent;
	}
	
	$(this).find('span').html(new_lang_line);
	$(this).find('.attendance-type').val(new_type);
	$(this).removeClass(type).addClass(new_type);
	
	$.post('tasks/attendance/change/' + $('#course-id').val(), "type=" + new_type + "&date=" + date + "&student_id=" + student_id + "&ajax=1", function(data) {
		if (data.status == "error") {
			$(this).find('span').html(lang_line);
			$(this).find('.attendance-type').val(type);
			$(this).removeClass(new_type).addClass(type);
			if (errorHandle(data)) return false;
		}
	}, "json");
});

